<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="班级" prop="classId">
        <el-select v-model="queryParams.classId" placeholder="请选择" clearable size="small">
          <el-option
            v-for="item in classList"
            :key="item.id"
            :label="item.label"
            :value="item.id"
            size="small">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="姓名" prop="studentName">
        <el-input type="text" v-model="queryParams.studentName" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="studentList">
      <el-table-column label="幼儿姓名" align="center" prop="studentName" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="过敏食材" align="center" prop="allergyFood" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
                     size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
          >修改</el-button>
         <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
         >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改学生对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="幼儿" prop="stuId">
          <el-select v-model="form.stuId" clearable filterable
            placeholder="请选择幼儿" @change="handleSelectChange">
            <el-option
              v-for="(item,index) in namelist"
              :key="index"
              :label="item.studentName"
              :value="item.id"
              size="small">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="过敏食材" prop="allergyFood">
          <el-button type="primary" @click="addIngredients">添加</el-button>
          <div v-for="(item,index) in tableData" :key="index">
            <div>
              <span>{{item.foodName}}</span><i  class="el-icon-circle-close" style="margin-left: 6px;cursor: pointer;" @click="handleDel(item,index)"></i>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加食材 -->
    <el-dialog
        title="添加食材"
        :visible.sync="dialogVisibleIngredient"
        width="60%"
        :before-close="handleCloseIngredient">
        <div class="add-ingredients">
          <div class="add-search">
            <el-input
                placeholder="请输入食材"
                prefix-icon="el-icon-search"
                v-model="ingredientName"
                @input="searchIngredient()">
            </el-input>
          </div>
          <el-row>
            <el-col :span="7">
              <div class="grid-content bg-purple" :style="'height:'+boxheight">
                <div class="above firstAbove"><div class="title">食材分类</div></div>
                <div class="under first_under">
                  <ul>
                    <li v-for="(dict,index) in dict.type.food_type" @click="changeRecipeSort(dict.value,dict.label)" :class="addActived==dict.value?'chooseStyle':''">
                      {{dict.label}}
                    </li>
                  </ul>
                </div>
              </div>
            </el-col>
            <el-col :span="7" style="padding:0 10px">
              <div class="grid-content bg-purple" :style="'height:'+boxheight">
                <div class="above">
                  <div class="title" style="width: 100%;position: relative;text-align: center;">食材列表
                  </div>
                </div>
                <div class="second_under">
                  <ul>
                    <li v-for="(item,index) in recipeList" >
                      <!-- <div class="left" @click="changeRecipeList(item.foodId,index)" :class="addListactived==index?'chooseStyle':''">
                        {{item.foodName}}
                      </div> -->
                      <div class="left" style="display:flex;" @click="changeRecipeList(item.foodId,index)" >
                        <div style="width:50px;height:50px"><img style="width:100%" :src="item.foodImage" alt=""></div>
                        <div style="display:flex;flex-direction: column;justify-content: space-between;margin-left:10px;width: 80%;" :class="addListactived==index?'chooseStyle':''">
                          <span>{{item.foodName}}</span>
                          <span>{{item.weight/1000}}(kg)</span>
                        </div>
                      </div>
                    </li>
                  </ul>
                </div>
              </div>
            </el-col>
            <el-col :span="3">
             <div style="height:100%;display:flex">
               <i class="el-icon-right"></i>
             </div>
            </el-col>
            <el-col :span="7" style="padding:0 10px">
              <div class="grid-content bg-purple" :style="'height:'+boxheight">
                <div class="above">
                  <div class="title" style="width: 100%;position: relative;text-align: center;">已选择的食材
                  </div>
                </div>
                <div class="second_under">
                  <ul>
                    <li v-for="(item,index) in choiceIngredientList" >
                      <div class="left" style="display:flex;">
                        <div style="width:50px;height:50px"><img style="width:100%" :src="item.foodImage" alt=""></div>
                        <div style="display:flex;flex-direction: column;justify-content: space-between;margin-left:10px">
                          <span>{{item.foodName}}</span>
                          <span>{{item.weight/1000}}(kg)</span>
                        </div>
                      </div>
                      <div  class="right" @click="delRecipeName(item.foodId,index)">
                        删除
                      </div>
                    </li>
                  </ul>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisibleIngredient = false">取 消</el-button>
          <el-button type="primary" @click="addIngredientHandle()">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>

import { addDevice, delDevice, listdevice, updateDevice } from '@/api/base/device'
import { addStudenPhoto, delstudenPhoto, editStudenPhoto, listAllergy, updatesphotoList,getAlbumByClassId,selectStudentName,delAllergy } from '@/api/base/grow'
import { addlistfood, dellistfood, listfood, updateFood,recipeListfood,selectClassifyList,addIngredient,editIngredient,addAllergy,editAllergy } from '@/api/base/grow'
import { selectClazz } from '@/api/base/clazz'
import { listPhotogl } from '@/api/base/gardensystem'
import AddgrowPhoto from '@/components/AddgrowPhoto/index'
import {selectName} from '@/api/base/device'
export default {
  name: "phonegl",
  dicts: ['year_type','classname_type'],
  components:{ AddgrowPhoto },
  dicts: ['food_type','cuisine_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        stuId:[
          { required: true, message: "不能为空", trigger: "blur" }
        ],
        allergyFood:[
          { required: true, message: "不能为空", trigger: "change" }
        ]
      },
      photoList:[],//弹窗照片数据
      totalPhoto:0,
      titlephoto:'',
      openphoto:false,
      classList:[],//班级
      queryParamsphoto: {
        pageNum: 1,
        pageSize: 10,
        // stuCode:null,
        stuId:null
      },
      showaddgrow:false,
      editqueryParams:{
        pageNum: 1,
        pageSize: 10,
        classId:null
      },
      edittotal:0,
      currentStudentList:[],
      url:null,
      id:null,//原来的学生号
      flagType:null,
      namelist:[],
      choiceIngredientList:[],
      dialogVisibleIngredient:false,
      ingredientName:'',
      highlightBd: true,
      addActived:null,//新增食材分类激活
      addListactived:null,//新增食材列表激活
      choiceIngredientList:[],
      majorNutrientShow: false,
      recipeList:[],
      boxheight:'',
      tableData:[],
      selectedStudent:{}
    };
  },
  created() {
    this.getList();
    //班级
    this.getQueryClazzList();
    this.getNamelist()
  },
  mounted(){
    //获取屏幕高度
    let that=this
    that.boxheight = document.documentElement.clientHeight - 164 + "px;";
    that.unheight=document.documentElement.clientHeight - 340 + "px;";
    window.onresize = function temp() {
      that.boxheight = document.documentElement.clientHeight - 164 + "px;";
      that.unheight=document.documentElement.clientHeight - 340 + "px;";
    };
  },
  methods: {
    /**删除食材列表**/
    async delfoodname(foodId){
      try {
        const data=await dellistfood(foodId)
        if(data.code==200){
          this.msgSuccess("删除成功");
          this.getList()
        }else{
          this.msgSuccess(data.msg);
        }
      }catch (e) {
        console.log(e)
      }
    },
    // 删除新增食谱库食材列表
    delRecipeName(foodId,index){
      this.choiceIngredientList.splice(index, 1);
    },
    // 新增食材-点击食材列表
    changeRecipeList(foodId,index){
      this.ingredientName = ''
      this.addListactived=index
      let chooseFood = this.recipeList.find(item => item.foodId === foodId);
      // 检查食物是否已存在于 choiceIngredientList 中
      let isFoodAlreadyChosen = this.choiceIngredientList.some(
        ingredient => ingredient.foodId === chooseFood.foodId
      );

      if (!isFoodAlreadyChosen) {
        this.choiceIngredientList.push(chooseFood);
        this.choiceIngredientList.forEach(item=>{
          if (item.foodImage && item.foodImage.startsWith("images/")) {
            item.foodImage = window.config.base_url+'/' + item.foodImage;
          }
        })
      }
    },
    async getAddList(){
      try {
        let params = {
          parentId: this.addActived,
          foodName: this.ingredientName
        }
        const {data}=await listfood(params)
        this.recipeList = data
        this.recipeList.forEach(item=>{
          if (item.foodImage && item.foodImage.startsWith("images/")) {
            item.foodImage = window.config.base_url+'/' + item.foodImage;
          }
        })
      }catch (e) {
        console.log(e)
      }
    },
    // 新增食材点击食材分类
    changeRecipeSort(value,name){
      this.ingredientName = ''
      this.addActived= value
      //调用食材列表接口
      this.getAddList()
    },
    // 添加食材-确定
    addIngredientHandle(){
      this.dialogVisibleIngredient = false;
      console.log('choiceIngredientList',this.choiceIngredientList);
      this.choiceIngredientList.forEach(item => {
      // 检查 tableData 中是否已存在该元素
      const existingItem = this.tableData.find(existingItem => existingItem.foodId === item.foodId);
        if (!existingItem) {
          // 如果不存在，则创建新对象并推入 tableData
          let newItem = {
            name: item.foodName,
            ...item
          };
          this.tableData.push(newItem);
        }
      });
    },
    searchIngredient(){
      this.addActived= null
      this.addListactived = null
      this.getAddList()
    },
    handleCloseIngredient() {
      this.dialogVisibleIngredient = false;
    },
    // 添加食材
    addIngredients(){
      this.dialogVisibleIngredient = true
      this.choiceIngredientList = []
    },
    handleSelectChange(value){
      this.selectedStudent = this.namelist.find(student => student.id === value);

    },
    /**查询用户列表*/
    async getNamelist(){
      try {
        const obj ={
          studentName:this.stuId
        }
        const data=await selectStudentName(obj)
        this.namelist=data.data
      } catch (e){
        console.log(e)
      }
    },
    /**修改 选择学生*/
    async clicktabel(e){
      // debugger;
      let params={
        id:this.id,
        // imgUrl:this.url,
        toStuId:e.stuId
      }
      const data = await editStudenPhoto(params).then(res=>{
        this.msgSuccess("修改成功");
        if(this.flagType){
          this.getphotolist(1)
        }else{
          this.getphotolist(2)
        }
        this.getList();
        console.log(this.$refs.popovertable)
        this.$refs.popovertable.doClose();
        document.body.click()

      })
      // if(data.code==200){
      //
      // }
    },
    /** 查询班级列表 */
    async getQueryClazzList() {
      try{
        this.loading = true;
        const {rows}=await selectClazz();
        this.classList=rows.map(item=>{
          return {
            id:item.id,
            label:item.title,
          }
        })
        this.loading = false;
      }catch (e) {
        console.log(e)
      }
    },
    /** 查询学生列表 */
    async getList() {
      try {
        this.loading = true;
        const data=await listAllergy(this.queryParams)
        this.studentList = data.rows;
        this.total = data.total;
        this.loading = false;
      }catch (e) {
        console.log(e)
      }
    },
    /**获取学生相册**/
    async getphotolist(val){
      try {
        const data= val === 1  ? await updatesphotoList(this.queryParamsphoto) : await getAlbumByClassId(this.queryParamsphoto)
        this.photoList=data.rows
        this.totalPhoto=data.total
      }catch (e) {
        console.log(e)
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.open = true
      this.reset();
      this.form = row
      const id = row.id || this.ids
      let foodNamesArray = row.allergyFood.split(',');
      // 创建一个包含foodName字段的对象数组
      this.tableData = foodNamesArray.map(name => ({ foodName: name.trim() }));
      this.title = "修改幼儿过敏食材";

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.tableData = []
      this.reset();
      this.open = true
      this.title='新增幼儿过敏食材'
    },

    /** 提交按钮 */
    submitForm() {
      let foodNamesArray = this.tableData.map(item => item.foodName);
      this.form.allergyFood = foodNamesArray.join(",")
      this.form.classId =this.selectedStudent.classId
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            editAllergy(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAllergy(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDel(item,index){
      this.tableData.splice(index,1)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delAllergy(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },

    // 表单重置
    // resetphoto() {
    //   this.formphoto = {
    //
    //   };
    //   this.resetForm("formphoto");
    // },
    // 取消照片按钮
    cancelPhoto() {
      this.openphoto = false;
      this.resetphoto();
    },
  }
};
</script>
<style lang="scss" scoped>
.el-dialog .el-image{
  left: 50%;
  transform: translate(-50%,0);
}
.radiostyle{
  position: absolute;
  z-index: 10;
  right: 10px;
  top: 10px;
}
</style>

<style lang="scss" scoped>
::v-deep .el-upload__tip{
  display: none;
}
ol, ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
.app-container{
  .grid-content{
    border: 1px solid #ccc;
    border-radius: 5px;
    .above,.third_above{
      border-bottom: 1px solid #ccc;
      font-weight: 700;
      font-style: normal;
      font-size: 18px;
      display: flex;
      -webkit-box-orient: vertical;
      -webkit-box-direction: normal;
      -ms-flex-direction: column;
      flex-direction: column;
      -webkit-box-align: center;
      -ms-flex-align: center;
      align-items: center;
      justify-content: center;
      height: 14%;
      .title{
        margin: 20px 0;
      }
    }
    .first_under,.second_under{
      height: 86%;
      overflow: auto;
    }

    .under ul{
      padding: 10px;
      overflow: auto;
      li{
        font-size: 14px;
        padding: 12px 0;
        cursor: pointer;
      }
      .chooseStyle{
        color: #fff;
        background-color: #f60;
      }
    }
    .second_under ul{
      padding: 10px;
      li{
        font-size: 14px;
        cursor: pointer;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-pack: justify;
        -ms-flex-pack: justify;
        justify-content: space-between;
        .left{
          width: 100%;
          padding: 12px 0;
          padding-left: 10px;
        }
        .right{
          width: 30%;
          padding: 12px 0;
          text-align: center;
          color: #f60;
        }
      }
      .chooseStyle{
        color: #fff;
        background-color: #f60;
      }
    }
    .third_above{
      min-height: 120px;
      border-bottom: 1px solid #ccc;
      .special_Input{
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -ms-flex-wrap: wrap;
        flex-wrap: wrap;
        padding: 0 10px;
      }
    }
    .third_under{
      padding: 20px;
      overflow: auto;
      .one_part{
        .head{
          font-size: 16px;
          margin-bottom: 15px;
        }
        .info{
          display: flex;
          flex-wrap: wrap;
          .each{
            width: 50%;
            display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            .foot{
              font-size: 14px;
              color: #606266;
              height: 40px;
              line-height: 40px;
              width: 108px;
            }
          }
        }
      }
      .control{
        text-align: right;
      }
    }
    .add-ingredient{
      position: absolute;
      right: 20px;
      bottom: 0;
      top: 0;
      margin: auto;
    }
    .third_center_table{
      padding: 20px;
      border-bottom: 1px solid #ccc;
      .head{
        padding-bottom: 20px;
      }
    }

  }
}
.add-ingredients{
  width: 100%;
  .add-search{
    margin-bottom: 10px;
  }
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label{
  color: #606266!important;
}
::v-deep .el-checkbox__input.is-checked + .el-checkbox__label:hover{
  color: #606266!important;
}
::v-deep .el-transfer-panel{
  width: 300px;
}
::v-deep .el-checkbox.el-transfer-panel__item{
  width: 80%;
}
::v-deep .el-transfer-panel__body{
  height: 80%;
}
::v-deep .el-transfer-panel__list.is-filterable{
  height: 100%;
}
::v-deep .el-transfer-panel__item{
  padding:0 10px;
  height: 60px;
  display: flex !important;
  align-items: center;
  .el-checkbox__input{
    position: relative;
    top: 0px;
  }
}
::v-deep .el-transfer__buttons{
    display: flex;
    align-items: center;
    justify-content: center;
    border-top: 1px solid #e6ebf5;
    border-bottom: 1px solid #e6ebf5;
}
::v-deep .el-transfer__button:first-child{
  margin-bottom:0px
}
::v-deep .el-dialog__footer{
  text-align: center;
}
// 修改高亮背景色和color
::v-deep .el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content {
  background-color: #8cc8ff;
  color: #fff;
}
</style>


